package AVLTree;

import org.omg.CORBA.NO_IMPLEMENT;

import java.util.ArrayList;
import java.util.List;

public class AvlTree<K extends Comparable<K>, V> implements Map<K, V> {

    private class Node {
        private K key;
        private V val;
        private Node left, right;
        private int height;

        private Node(K key, V val) {
            this.key = key;
            this.val = val;
        }
    }

    private Node root;
    private int size;

    public AvlTree() {
        root = null;
        size = 0;
    }

    @Override
    public int getSize() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public void add(K key, V val) {

        root = add(root, key, val);
    }

    private Node add(Node node, K key, V val) {
        if (node == null) {
            size++;
            return new Node(key, val);
        }

        if (node.key.compareTo(key) < 0) {
            node.right = add(node.right, key, val);

        } else {
            node.left = add(node.left, key, val);
        }

        //跟新height
        node.height = Math.max(getHeight(node.left), getHeight(node.right)) + 1;

        int balanceFactor = getBalanceFactor(node);

        //平衡维护
        //LL
        if (balanceFactor > 1 && getBalanceFactor(node.left) >= 0) {
            return rightRotate(node);
        }

        //RR
        if(balanceFactor < -1 && getBalanceFactor(node.right) <= 0){
            return leftRotate(node);
        }

        //LR
        if(balanceFactor >1 && getBalanceFactor(node.left) < 0){
            node.left = leftRotate(node.left);
            return rightRotate(node);
        }

        //RL
        if(balanceFactor < -1 && getBalanceFactor(node.right) > 0){
            node.right = rightRotate(node.right);
            return leftRotate(node);
        }

        return node;
    }

    // 对节点y进行向右旋转操作，返回旋转后新的根节点x
    //        y                              x
    //       / \                           /   \
    //      x   T4     向右旋转 (y)        z     y
    //     / \       - - - - - - - ->    / \   / \
    //    z   T3                       T1  T2 T3 T4
    //   / \
    // T1   T2
    private Node rightRotate(Node y) {
        Node x = y.left;
        Node T3 = x.right;

        // 向右旋转过程
        x.right = y;
        y.left = T3;

        // 更新height
        y.height = Math.max(getHeight(y.left), getHeight(y.right)) + 1;
        x.height = Math.max(getHeight(x.left), getHeight(x.right)) + 1;

        return x;
    }

    // 对节点y进行向左旋转操作，返回旋转后新的根节点x
    //    y                             x
    //  /  \                          /   \
    // T1   x      向左旋转 (y)       y     z
    //     / \   - - - - - - - ->   / \   / \
    //   T2  z                     T1 T2 T3 T4
    //      / \
    //     T3 T4
    private Node leftRotate(Node y) {
        Node x = y.right;
        Node T2 = x.left;

        // 向左旋转过程
        x.left = y;
        y.right = T2;

        // 更新height
        y.height = Math.max(getHeight(y.left), getHeight(y.right)) + 1;
        x.height = Math.max(getHeight(x.left), getHeight(x.right)) + 1;

        return x;
    }

    private K minmum() {
        if (size == 0) {
            throw new IllegalArgumentException("BSTMap is empty");
        }

        return minmum(root).key;
    }

    private Node minmum(Node node) {
        if (node.left == null) {
            return node;
        }

        return minmum(node.left);
    }

    private K maxmum() {
        if (size == 0) {
            throw new IllegalArgumentException("BSTMap is empty");
        }

        return maxmum(root).key;
    }

    private Node maxmum(Node node) {
        if (node.right == null) {
            return node;
        }

        return maxmum(node.right);
    }

    public K removeMin() {
        if (size == 0) {
            throw new IllegalArgumentException("BSTMap is empty");
        }
        K res = minmum();
        root = removeMin(root);
        return res;
    }

    private Node removeMin(Node node) {
        if (node.left == null) {
            size--;
            return node.right;
        }

        node.left = removeMin(node.left);
        return node;
    }

    public K removeMax() {
        if (size == 0) {
            throw new IllegalArgumentException("BSTMap is empty");
        }
        K res = maxmum();
        root = removeMax(root);
        return res;
    }

    private Node removeMax(Node node) {
        if (node.right == null) {
            size--;
            return node.left;
        }

        node.right = removeMin(node.right);
        return node;
    }


    @Override
    public void remove(K key) {
        if (size == 0) {
            throw new IllegalArgumentException("BSTMap is empty");
        }
        root = remove(root, key);
        size--;
    }

    private Node remove(Node node, K key) {
        if (node == null) {
            return null;
        }

        Node retNode;

        if (key.compareTo(node.key) < 0) {
            node.left = remove(node.left, key);
            retNode = node;

        } else if (key.compareTo(node.key) > 0) {
            node.right = remove(node.right, key);
            retNode = node;

        } else {//key == node.key
            if (node.left == null) {
                retNode =  node.right;
            }

            if (node.right == null) {
                retNode =  node.left;
            }

            Node sucesstor = minmum(node.right);
            removeMin(node.right);
            node.key = sucesstor.key;
            node.val = sucesstor.val;
            retNode = node;
        }

        if(retNode == null){
            return null;
        }


        //跟新height
        retNode.height = Math.max(getHeight(retNode.left), getHeight(retNode.right)) + 1;

        int balanceFactor = getBalanceFactor(retNode);

        //平衡维护
        //LL
        if (balanceFactor > 1 && getBalanceFactor(retNode.left) >= 0) {
            return rightRotate(retNode);
        }

        //RR
        if(balanceFactor < -1 && getBalanceFactor(retNode.right) <= 0){
            return leftRotate(retNode);
        }

        //LR
        if(balanceFactor >1 && getBalanceFactor(retNode.left) < 0){
            retNode.left = leftRotate(retNode.left);
            return rightRotate(retNode);
        }

        //RL
        if(balanceFactor < -1 && getBalanceFactor(retNode.right) > 0){
            retNode.right = rightRotate(retNode.right);
            return leftRotate(retNode);
        }

        return retNode;

    }

    private Node getNode(Node node, K key) {
        if (node == null) {
            return null;
        }
        if (node.key.equals(key)) {
            return node;
        }

        if (node.key.compareTo(key) > 0) {
            return getNode(node.left, key);

        } else {
            return getNode(node.right, key);

        }
    }

    @Override
    public void set(K key, V val) {
        getNode(root, key).val = val;
    }

    @Override
    public V get(K key) {
        Node node = getNode(root, key);
        if (node == null) {
            return null;
        } else {
            return getNode(root, key).val;
        }
    }

    @Override
    public boolean contains(K key) {
        if (getNode(root, key) == null) {
            return false;
        } else {
            return true;
        }
    }

    //检查该树是否是二分搜索树
    @Override
    public boolean isBST() {

        List<K> list = new ArrayList<>();
        isBST(root, list);

        for (int i = 0; i < list.size() - 1; i++) {
            if (list.get(i).compareTo(list.get(i + 1)) > 0) {
                return false;
            }
        }
        return true;

    }

    //检查树是否为二分搜索树
    private Node isBST(Node node, List list) {

        if (node == null) {
            return null;
        }

        node.left = isBST(node.left, list);
        list.add(node.key);
        node.right = isBST(node.right, list);

        return node;
    }


    //检查树是否为平衡二叉树
    @Override
    public boolean isBalance() {
        return isBalance(root);
    }

    private boolean isBalance(Node node) {

        if(node == null){
            return true;
        }

        if (Math.abs(getBalanceFactor(node)) > 1) {
            return false;
        }
        return isBalance(node.left) && isBalance(node.right);
    }

    //获取节点的平衡因子
    private int getBalanceFactor(Node node) {
        if (node == null) {
            return 0;
        }
        return (getHeight(node.left) - getHeight(node.right));
    }

    //获取节点的高度
    private int getHeight(Node node) {

        if (node == null) {
            return 0;
        }

        return node.height;

    }

}
